package com.chaos.payment.service.pay.balance;

import java.time.LocalDateTime;

import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONUtil;
import com.chaos.framework.model.dto.result.data.DataResult;
import com.chaos.payment.service.TPayFlowService;
import com.chaos.order.api.dto.pay.request.PayRequest;
import com.chaos.order.api.dto.pay.request.RefundRequest;
import com.chaos.order.api.dto.pay.response.PayResponse;
import com.chaos.order.api.dto.pay.response.RefundResponse;
import com.chaos.payment.entity.TPayFlow;
import com.chaos.payment.service.pay.AbstractPay;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @description:
 * @author: crayon
 * @time: 2024/6/17 18:19
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class BalancePayApi extends AbstractPay<PayRequest, RefundRequest> {

    private final TPayFlowService payFlowService;

    @Override
    @Transactional(rollbackFor = Exception.class ,timeout = 30000)
    public DataResult<PayResponse> pay(PayRequest request) {
        PayResponse payResponse = new PayResponse();
        String orderNo = request.getOrderNo();
        Integer orderType = request.getOrderType();
        Long userId = request.getUserId();
        Assert.notBlank(orderNo, "订单号不能为空");
        Assert.notNull(orderType, "订单类型不能为空");
        Assert.notNull(orderType, "订单类型不能为空");
        //查询订单流水
        TPayFlow tPayFlow = payFlowService.selectByOrderNo(orderNo);
        if (Objects.nonNull(tPayFlow)) {
           // Assert.isTrue(tPayFlow.getStatus() == OrderEnums.OrderPayStatusEnum.TO_BE_PAID.getValue(), "订单已支付，无需再次支付");
        } else {
            tPayFlow = initFlow(request);
        }
        // 开始支付
        toPay(request, userId, tPayFlow);

        tPayFlow.setId(tPayFlow.getId());
      //  payResponse.setPayStatus(OrderEnums.OrderPayStatusEnum.PAID.getValue());
        return DataResult.ok(payResponse);
    }

    private void toPay(PayRequest request, Long userId, TPayFlow tPayFlow) {
        log.info("topay request:{} userId:{} tPayFlow:{} ", JSONUtil.toJsonStr(request), userId, JSONUtil.toJsonStr(tPayFlow));
//        TUserBalance tUserBalance = userBalanceService.selectByUserId(request.getUserId());
//        BigDecimal beforeBalance = tUserBalance.getTotalBalance();
//        Assert.notNull(tUserBalance, "用户余额账户不存在");
//        Assert.isTrue(tUserBalance.getStatus() == TUserBalance.STATUS_OF_ON, "账户余额已禁用");
//        //行锁
//        TUserBalance userBalance = userBalanceService.lockUserBalance(tUserBalance.getId());
//        Assert.isTrue(userBalance.getTotalBalance().compareTo(request.getPayAmount()) >= 0, "用户余额不足");
//        // 扣款
//        BigDecimal afterBalance = userBalance.getTotalBalance().subtract(request.getPayAmount());
//        userBalance.setTotalBalance(afterBalance);
//        userBalanceService.updateById(userBalance);
//        //写入余额流水
//        TUserBalanceFlow tUserBalanceFlow = saveBalanceFlow(request, userId, beforeBalance, afterBalance);
        //更新订单状态，更流水状态
        updateOrder(request);
        //更新支付流水
        TPayFlow updateFlow = new TPayFlow();
        updateFlow.setId(tPayFlow.getId());
       // updateFlow.setThirdFlowNo(tUserBalanceFlow.getId().toString());
       // updateFlow.setStatus(OrderEnums.OrderPayStatusEnum.PAID.getValue());
        payFlowService.updateById(updateFlow);
    }

    private void updateOrder(PayRequest request) {
//        AbstractOrder orderHandler = unifiedOrderService.getOrderHandler(request.getOrderType());
//        //更新订单支付状态
//        UnifiedXsnOrderDto baseUnifiedOrderDto = new UnifiedXsnOrderDto();
//        baseUnifiedOrderDto.setOrderNo(request.getOrderNo());
//        baseUnifiedOrderDto.setStatus(OrderEnums.OrderPayStatusEnum.PAID.getValue());
//        baseUnifiedOrderDto.setPayAmount(request.getPayAmount());
//        baseUnifiedOrderDto.setTotalAmount(request.getTotalAmount());
//        baseUnifiedOrderDto.setPayTime(LocalDateTime.now());
//        orderHandler.updateOrder(baseUnifiedOrderDto);
    }

    private TPayFlow initFlow(PayRequest request) {
        TPayFlow tPayFlow = new TPayFlow();
        tPayFlow.setOrderNo(request.getOrderNo());
        tPayFlow.setOrderType(request.getOrderType());
        tPayFlow.setMerchantId(request.getMerchantId());
        tPayFlow.setUserId(request.getUserId());
        tPayFlow.setThirdOrderNo("");
        tPayFlow.setThirdFlowNo("");
        tPayFlow.setTotalAmount(request.getPayAmount());
        tPayFlow.setChannel(request.getChannel());
        tPayFlow.setPayType(request.getPayType());
        tPayFlow.setPayTime(LocalDateTime.now());
        tPayFlow.setPayTradeType(request.getPayTradeType());
        payFlowService.save(tPayFlow);
        return tPayFlow;
    }


    @Override
    public DataResult<PayResponse> payQuery(PayRequest request) {
        return null;
    }

    @Override
    public DataResult<PayResponse> payCancel(PayRequest request) {
        return null;
    }

    @Override
    public DataResult<RefundResponse> refund(RefundRequest request) {
        return null;
    }

    @Override
    public DataResult<RefundResponse> refundQuery(RefundRequest request) {
        return null;
    }

    @Override
    public Boolean verifySign(String jsonObject, Integer verifyType) {
        return null;
    }
}
